package com.hpin.fansea.ui;

import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hpin.fansea.R;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.utils.LogUtil;
import com.lidroid.xutils.http.RequestParams;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * 忘记密码
 * Created by Aaron on 15/9/8.
 */
public class ChangePswActivity extends BaseActivity {

    private EditText et_phone;// 手机号
    private EditText et_code;// 验证码
    private EditText et_psw;// 新的密码
    private EditText et_psw2;// 新的密码
    private Button btn_rification;// 验证码btn
    private Button btn_change_psw;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_change_psw);

        mApplication.addActivity(this);

        initWidget();

    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.exchange_psw));

        et_phone = (EditText) findViewById(R.id.et_change_phone);
        et_code = (EditText) findViewById(R.id.et_change_code);
        et_psw = (EditText) findViewById(R.id.et_change_psw);
        et_psw2 = (EditText) findViewById(R.id.et_change_psw2);

        btn_rification = (Button) findViewById(R.id.btn_change_rification);
        btn_change_psw = (Button) findViewById(R.id.btn_change_psw);


//        LogUtil.e("TAG", "主线程==" + Thread.currentThread().getName());

        iv_left.setOnClickListener(this);
        btn_rification.setOnClickListener(this);
        btn_change_psw.setOnClickListener(this);
    }


    /**
     * 重置密码
     */
    private void resetPsw() {

        String phone = et_phone.getText().toString().trim();
        String psw = et_psw.getText().toString().trim();
        String psw2 = et_psw2.getText().toString().trim();
        String code = et_code.getText().toString().trim();

        if (CommonUtils.isNull(phone)) {
            Toast.makeText(this, "请填写手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!CommonUtils.isPhone(phone)) {
            Toast.makeText(this, "请填写正确的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (CommonUtils.isNull(psw)) {
            Toast.makeText(this, "请填写密码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (psw.length() > 16 || psw.length() < 6) {
            Toast.makeText(getApplicationContext(), "密码应在6-16位",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (CommonUtils.isNull(code)) {
            Toast.makeText(this, "请填写验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!psw.equals(psw2)) {
            Toast.makeText(this, "两次输入密码不一样！", Toast.LENGTH_SHORT).show();
            return;
        }

//            DataService.resetPsw(this, handler, phone, CommonUtils.toMd5(psw.getBytes()), code);
        //验证验证码
        //提交验证
        SMSSDK.submitVerificationCode("86", et_phone.getText().toString().trim(), et_code.getText().toString().trim());

    }

    /**
     * 重置密码
     */
    private void resetPassword() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("password", CommonUtils.toMd5(et_psw.getText().toString().trim().getBytes()));
        params.addBodyParameter("verifycode", et_code.getText().toString().trim());

        HttpUtil.getInstance().setPostRequest("修改中...", this, Constant.WEB_ROOT + Constant.RESETPASSWORD + et_phone.getText().toString().trim(),
                params, new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {


                    }
                }, null);

    }

    /**
     * 获取验证码
     */
    private void checkVer() {

        if (CommonUtils.isNull(et_phone.getText().toString().trim())) {
            Toast.makeText(this, "请填写手机号码", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!CommonUtils.isPhone(et_phone.getText().toString().trim())) {
            Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }

        //倒计时
        countDown();

        //获取验证码
        getSms();

//        if (checkNet(ctx)) {
//            // 验证码按钮不可点击
//            btn_rification.setClickable(false);
//            showProgress("获取验证码");
//            DataService.resetPswCode(this, handler, phone);
//        } else {
//            showToast(Constant.ErrorMessage.NETWORK_EXCEPTION_ERROR);
//        }
    }

    private void getSms() {

        EventHandler eventHandler = new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
//                show.dismiss();
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成

                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码验证成功
                        LogUtil.d("sms", "==========提交验证码成功 =========");

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //验证码验证成功,重置密码
                                resetPassword();
                            }
                        });
//                        Thread.currentThread().getName();

                        LogUtil.e("tag", "线程====>>>>" + Thread.currentThread().getName());


                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        //获取验证码成功
                        LogUtil.d("sms", "==========获取验证码成功 =========");

                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }
                } else {
                    //验证失败
                    showToast("验证码错误");
                }
            }
        };

        // 注册回调监听接口
        SMSSDK.registerEventHandler(eventHandler);
        //提交发送短信的请求
        SMSSDK.getVerificationCode("86", et_phone.getText().toString().trim());
        ready = true;

    }

    protected void onDestroy() {
        if (ready) {
            // 销毁回调监听接口
            SMSSDK.unregisterAllEventHandler();
        }
        super.onDestroy();
    }

    /**
     * 倒计时
     */
    private void countDown() {

        btn_rification.setClickable(false);
        btn_rification.setEnabled(false);
        if (executor == null) {
            executor = Executors.newSingleThreadExecutor();
        }

        btn_rification.setText(currentTime + " 秒");
        for (int i = 0; i < 60; i++) {

            executor.execute(new Runnable() {

                @Override
                public void run() {

                    SystemClock.sleep(1000);

                    changeTime();
                }
            });

        }

    }

    private int currentTime = 60;
    private ExecutorService executor;
    private boolean ready;

    /**
     * 改变界面时间
     */
    private void changeTime() {
        runOnUiThread(new Runnable() {
            public void run() {

                if (currentTime == 1) {
                    currentTime = 60;
                    btn_rification.setText(getResources().getString(R.string.get_code));
                    btn_rification.setClickable(true);
                    btn_rification.setEnabled(true);

                } else {
                    btn_rification.setText(--currentTime + " 秒");
                }
            }
        });
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {

            case R.id.iv_left:
                finish();
                break;
            case R.id.btn_change_psw:
                // 重置密码按钮
                resetPsw();
                break;
            case R.id.btn_change_rification:
                // 获得验证码
                checkVer();
                break;
            default:
                break;
        }
    }
}
